<?php
/**
 * @title 93. 复原IP地址 - 迭代
 * @author start2004
 */

// ini_set("memory_limit", "128M");


class Solution {

    /**
     * @param String $s
     * @return String[]
     */
    function restoreIpAddresses($s) {
        /**
         * @since 2020-08-10 空格
         */
        $zeros = [
            1 => "",
            2 => "00",
            3 => "000",
        ];

        /**
         * @since 2020-08-10 过程集
         */
        $result = [
            [[], $s,],
        ];

        /**
         * @since 2020-08-10 4个整数
         */
        for ($i=0; $i<4; $i++){
            // echo str_repeat(PHP_EOL, 3), "i={$i}", PHP_EOL;

            /**
             * @since 2020-08-10 下次循环集合
             */
            $nextResult = [];

            /**
             * @since 2020-08-10 遍历处理
             */
            foreach ($result as list($ips, $s)){
                // echo "ips=[", implode(".", $ips) ,"], s={$s}", PHP_EOL;

                /**
                 * @since 2020-08-10 整数长度从1到3位
                 */
                for ($j=1; $j<=min(3, strlen($s)); $j++){
                    $ip = substr($s, 0, $j);
                    if($ip <= 255 AND ($j==1 OR ($j>=2 AND $ip[0] != "0"))){
                        // echo "j={$j}, ip={$ip}, next_s=", substr($s, $j), PHP_EOL;
                        $ips[$i] = $ip;
                        $nextResult[] = [$ips, substr($s, $j)];
                    } else {}
                }
            }

            /**
             * @since 2020-08-10 下次循环, 一共也就4次, 不用break
             */
            $result = $nextResult;
        }
        // return $result;

        /**
         * @since 2020-08-10 取出所有可能性
         */
        $ipArray = [];
        foreach ($result as list($ips, $s)){
            if($s == ""){
                $ipArray[] = implode(".", $ips);
            } else {}
        }

        /**
         * @return
         */
        return $ipArray;
    }
}


/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.09.php
 */
$datas = [
    "25525511135",
    "010010",
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->restoreIpAddresses($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
